using System;
using System.Net;
using System.Net.Http;
using System.IO;
using System.Text;
using System.Windows.Forms;
using CCWin;
using Newtonsoft.Json;

namespace Mes.质检管理.ReinspectionCheck
{
    public partial class ReinspectionDetail : Skin_DevExpress
    {
        public string InspectionNo { get; set; }
        public int InspectionId { get; set; }
        public string Supplier { get; set; }
        public string InspectionDate { get; set; }
        public string MaterialName { get; set; }

        private const string API_BASE = "/api/Inspection";

        public ReinspectionDetail()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            // 显示基本信息
            lblInspectionNoVal.Text = InspectionNo ?? string.Empty;
            lblSupplierVal.Text = Supplier ?? string.Empty;
            lblDateVal.Text = InspectionDate ?? string.Empty;
            lblMaterialNameVal.Text = MaterialName ?? string.Empty;

            // 根据质检ID查询复检信息
            if (InspectionId > 0)
            {
                LoadReinspectionData();
            }
            else
            {
                MessageBox.Show("质检ID为空，无法查询复检数据", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void LoadReinspectionData()
        {
            try
            {
                string url = HttpClientHelper.GetApiUrl("/api/Inspection/GetReinspectionByCheckId") + $"?CheckId={InspectionId}";
                var json = HttpGet(url);
                
                // 添加调试信息
                System.Diagnostics.Debug.WriteLine($"API URL: {url}");
                System.Diagnostics.Debug.WriteLine($"API Response: {json}");
                
                var resp = JsonConvert.DeserializeObject<MaterialChenck.ApiResult<ReinspectionModel>>(json);
                if (resp != null && resp.code == 200 && resp.data != null)
                {
                    var data = resp.data;
                    
                    // 添加调试信息
                    System.Diagnostics.Debug.WriteLine($"QualificationStatus: '{data.QualificationStatus}'");
                    System.Diagnostics.Debug.WriteLine($"Remarks: '{data.Remarks}'");
                    
                    // 填充复检基本信息
                    lblReinspectionNoVal.Text = data.ReinspectionNo ?? "-";
                    lblReinspectionDateVal.Text = data.ReinspectionDate.ToString("yyyy-MM-dd");
                    lblReinspectorVal.Text = data.Reinspector ?? "-";
                    
                    // 填充复检结果信息
                    lblReinspectionQuantityVal.Text = data.ReinspectionQuantity.ToString();
                    
                    // 根据合格状态计算合格数和不合格数
                    if (data.QualificationStatus == "合格")
                    {
                        lblRequalifiedQuantityVal.Text = data.ReinspectionQuantity.ToString();
                        lblReunqualifiedQuantityVal.Text = "0";
                    }
                    else
                    {
                        lblRequalifiedQuantityVal.Text = "0";
                        lblReunqualifiedQuantityVal.Text = data.ReinspectionQuantity.ToString();
                    }
                    
                    lblReinspectionResultVal.Text = string.IsNullOrEmpty(data.QualificationStatus) ? "-" : data.QualificationStatus;
                    lblReinspectionRemarksVal.Text = string.IsNullOrEmpty(data.Remarks) ? "-" : data.Remarks;
                    
                    // 根据复检结果决定是否显示销毁按钮
                    btnDestroy.Visible = data.QualificationStatus == "不合格";
                }
                else
                {
                    // 静默处理，不显示弹窗
                    System.Diagnostics.Debug.WriteLine($"未找到复检信息: {resp?.message} (Code: {resp?.code})");
                }
            }
            catch (Exception ex)
            {
                // 静默处理，不显示弹窗
                System.Diagnostics.Debug.WriteLine($"加载复检数据失败：{ex.Message}");
            }
        }

        private string HttpGet(string url)
        {
            try
            {
                // 使用HttpClient直接调用接口
                using (var httpClient = new HttpClient())
                {
                    // 设置超时时间
                    httpClient.Timeout = TimeSpan.FromSeconds(30);
                    
                    // 发送GET请求
                    var response = httpClient.GetAsync(url).Result;
                    
                    // 检查响应状态
                    if (response.IsSuccessStatusCode)
                    {
                        // 读取响应内容
                        return response.Content.ReadAsStringAsync().Result;
                    }
                    else
                    {
                        // 处理错误响应
                        string errorContent = response.Content.ReadAsStringAsync().Result;
                        Console.WriteLine($"API调用失败: {response.StatusCode} - {errorContent}");
                        return null;
                    }
                }
            }
            catch (Exception ex)
            {
                // 处理异常
                Console.WriteLine($"调用接口时发生错误: {ex.Message}");
                return null;
            }
        }

        private void btnDestroy_Click(object sender, EventArgs e)
        {
            try
            {
                // 这里可以调用销毁API
                // string destroyUrl = $"{API_BASE}/DestroyProduct?InspectionId={InspectionId}";
                // var destroyResult = HttpPost(destroyUrl, "");
                
                // 直接执行销毁操作，关闭详情页面
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                // 静默处理，不显示弹窗
                System.Diagnostics.Debug.WriteLine($"销毁操作失败：{ex.Message}");
            }
        }
    }

    public class ReinspectionModel
    {
        public int Id { get; set; }
        public string ReinspectionNo { get; set; }
        public string ReinspectionName { get; set; }
        public DateTime ReinspectionDate { get; set; }
        public string Reinspector { get; set; }
        public int ReinspectionQuantity { get; set; }
        public string QualificationStatus { get; set; }  // 对应后端的合格状态字段
        public string Remarks { get; set; }  // 对应后端的备注字段
        public int ChenckId { get; set; }  // 对应后端的质检ID字段
    }
}
